package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.io.File;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoTakeBinding;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.WorkPathUtil;

public class VideoTakeActivity extends BaseAc<ActivityVideoTakeBinding> {

    private Handler mhandler;
    private int mRecordTime;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_take;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoTakeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mDataBinding.ivVideoTakeStart.setOnClickListener(this);
        mDataBinding.ivVideoTakeReversal.setOnClickListener(this);
        mhandler = new Handler();
        mRecordTime = 0;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivVideoTakeStart:
                if (mDataBinding.cameraView.isTakingVideo()) {
                    mDataBinding.cameraView.stopVideo();
                } else {
                    String filePath = WorkPathUtil.generateVideoFilePath(null);
                    if (filePath != null) {
                        mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                    }
                }
                break;
            case R.id.ivVideoTakeReversal:
                Facing curFacing = mDataBinding.cameraView.getFacing();
                if (curFacing == Facing.BACK) {
                    mDataBinding.cameraView.setFacing(Facing.FRONT);
                } else {
                    mDataBinding.cameraView.setFacing(Facing.BACK);
                }
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.VIDEO);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                super.onCameraOpened(options);
            }

            @Override
            public void onVideoRecordingStart() {
                //开始
                mDataBinding.tvVideoTakeTime.setText("00:00:00");
                mDataBinding.tvVideoTakeTime.setTextColor(Color.parseColor("#FF202020"));
                mDataBinding.tvVideoTakeTime.setBackgroundResource(R.drawable.shape_take_time);
                mDataBinding.ivVideoTakeStart.setImageResource(R.drawable.an_lx2);
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //结束
                mDataBinding.tvVideoTakeTime.setText("00:00:00");
                mDataBinding.tvVideoTakeTime.setTextColor(Color.parseColor("#FFFFFFFF"));
                mDataBinding.tvVideoTakeTime.setBackgroundResource(0);
                mDataBinding.ivVideoTakeStart.setImageResource(R.drawable.an_lx1);
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                //生成水印视频
                showDialog(getString(R.string.save_video_ing));
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, result.getFile().getPath());
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_to_album);
                    }
                }, 500);
            }
        });
    }

    //开始拍摄
    private void startRecordTime() {
        mRecordTime = 0;
        mhandler.removeCallbacks(mUpdateRecordTimeTask);
        mhandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄
    private void stopRecordTime() {
        mhandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoTakeTime.setText(TimeUtil.getMmss(mRecordTime * 1000L));
            mhandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

}